﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Amib.Threading;
using System.Net;
using System.IO;
using log4net;
using System.Reflection;
using Util;

namespace WebCollection
{
    class ImgDownloader : IDisposable
    {
        private static ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private SmartThreadPool SMT = new SmartThreadPool(20, 3, 3);



        public void AddToThreadPool(string url, string filepath)
        {
            smtparam sp = new smtparam(new Uri(url), filepath);
            SMT.QueueWorkItem(new WorkItemInfo { Timeout = 600000 }, DownImg, sp);
        }


        private DateTime DtPrev = DateTime.Now;
        private object DownImg(object p)
        {

            smtparam sp = p as smtparam;
            Uri uri_Img = sp.uri_img;
            string filepath = sp.filepath;
            WebRequest request = null;
            WebResponse response = null;
            Stream reader = null;
            FileStream writer = null;


            try
            {
                request = WebRequest.Create(uri_Img);
                request.Timeout = 60000;//若30秒无响应则放弃

                response = request.GetResponse();
                reader = response.GetResponseStream();
                writer = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Write);
                byte[] buff = new byte[512];
                int c = 0; //实际读取的字节数
                while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                {
                    writer.Write(buff, 0, c);
                }
                Console.Write(".");
            }
            catch (Exception e)
            {
                log.Warn(e.Message);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            return null;
        }

        public void EndAllTask()
        {
            SMT.WaitForIdle();
        }

        internal class smtparam
        {
            public Uri uri_img { get; set; }
            public string filepath { get; set; }

            public smtparam(Uri uri_img, string filepath)
            {
                this.uri_img = uri_img;
                this.filepath = filepath;
            }
        }

        public void Dispose()
        {
            if (SMT != null)
            {
                SMT.Dispose();
            }
        }
    }
}
